package com.gxuwz.check.dao.admin.impl;

import com.gxuwz.check.base.BaseDao;
import com.gxuwz.check.dao.admin.IStudentDao;
import com.gxuwz.check.model.dto.StudentDto;
import com.gxuwz.check.model.entity.SysStudentEntity;
import com.gxuwz.check.model.entity.SysUserEntity;
import com.gxuwz.check.util.PageBean;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Repository
public class StudentDaoImpl extends BaseDao implements IStudentDao {
    @Override
    @Transactional
    public List<StudentDto> list(int page, int classId, int peopleNum) {
        /**
         * 人数不为0，代表是随机抽查
         */
        Criteria criteria = getSession().createCriteria(SysStudentEntity.class);
        //根据班级来查询
        if (classId != 0) {
            criteria.add(Restrictions.eq("classId", classId));
        }

            criteria.setFirstResult((page - 1) * new PageBean<>().getPageSize());
            criteria.setMaxResults(new PageBean<>().getPageSize());

        List<SysStudentEntity> list = criteria.list(); //学生列表
        List<StudentDto> listDto = new ArrayList<>(); //用于封装学生信息
        for (int i = 0; i < list.size(); i++) {
            StudentDto studentDto = new StudentDto();
            String hql = "select c.className from SysClassEntity c where classId = ?"; //查出学生的所属班级
            List listClass = getHibernateTemplate().find(hql, list.get(i).getClassId());
            String hql2 = "select u.userName from SysUserEntity u where userId = ?"; //学生的账号（学号）
            List listUserName = getHibernateTemplate().find(hql2, list.get(i).getUserId());
            studentDto.setId(i+1);
            studentDto.setStudentId(list.get(i).getStudentId());
            studentDto.setUserId(list.get(i).getUserId());
            studentDto.setUserName((String) listUserName.get(0)); //学生的账号
            if (list.get(i).getStudentSex() == 1) {
                studentDto.setStudentSex("男");
            } else {
                studentDto.setStudentSex("女");
            }
            studentDto.setStudentName(list.get(i).getStudentName());
            studentDto.setClassName((String) listClass.get(0));
            studentDto.setTel(list.get(i).getStudentTel());
            listDto.add(studentDto);
        }
        SessionClose();
        return listDto;
    }

    @Override
    @Transactional
    public List<StudentDto> listRandom(int classId, int peopleNum) {
        //查出一个班级里所有学生的id
        String hqlPeopleNum = "select s.userId from SysStudentEntity s where classId = ?";
        List listPeople = getHibernateTemplate().find(hqlPeopleNum,Integer.valueOf(classId));
        Random random = new Random();
        Set<Integer> set = new HashSet<>();
        List resultList = new ArrayList<>();
        while (set.size() < peopleNum){
            set.add((Integer) listPeople.get(random.nextInt(listPeople.size())));
        }
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            int next = (int) iterator.next();
            resultList.add(next);
        }
        List<SysStudentEntity> listStu = new ArrayList();
        for (int i = 0 ; i < resultList.size() ; i ++){
            try {
                Criteria criteria = getSession().createCriteria(SysStudentEntity.class);
                criteria.add(Restrictions.eq("userId",resultList.get(i)));
                List<SysStudentEntity> list1 = criteria.list();
                listStu.add(list1.get(0));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        List<StudentDto> listDto = new ArrayList<>(); //用于封装学生信息
        for (int j = 0 ; j < listStu.size() ; j++){
            try {
                StudentDto studentDto = new StudentDto();
                String hql = "select c.className from SysClassEntity c where classId = ?"; //查出学生的所属学院
                List listClass = getHibernateTemplate().find(hql, listStu.get(j).getClassId());
                String hql2 = "select u.userName from SysUserEntity u where userId = ?"; //学生的账号（学号）
                List listUserName = getHibernateTemplate().find(hql2, listStu.get(j).getUserId());
                studentDto.setStudentId(listStu.get(j).getStudentId());
                studentDto.setUserId(listStu.get(j).getUserId());
                studentDto.setUserName((String) listUserName.get(0)); //学生的账号
                if (listStu.get(j).getStudentSex() == 1) {
                    studentDto.setStudentSex("男");
                } else {
                    studentDto.setStudentSex("女");
                }
                studentDto.setStudentName(listStu.get(j).getStudentName());
                studentDto.setClassName((String) listClass.get(0));
                studentDto.setTel(listStu.get(j).getStudentTel());
                listDto.add(studentDto);
            }catch (RuntimeException e){
                e.printStackTrace();
            }

        }
        SessionClose();
        return listDto;
    }

    @Override
    public SysStudentEntity findStudentById(Integer studentId) {
        Criteria criteria = getSession().createCriteria(SysStudentEntity.class);
        criteria.add(Restrictions.eq("studentId",studentId));
        SysStudentEntity sysStudentEntity = (SysStudentEntity) criteria.list().get(0);
        SessionClose();
        return sysStudentEntity;
    }

    @Override
    public void delete(Integer studentId) {
        String sql = "delete from sys_student where student_id = '"+studentId+"'";
        getSession().createSQLQuery(sql).executeUpdate();
        SessionClose();
    }

    @Override
    public void edit() {

    }

    @Override
    @Transactional
    public void save(SysStudentEntity sysStudentEntity) {
        String sqlUser = "insert into sys_user(user_name,password,role_id) value('"+sysStudentEntity.getStudentTel()+"',123456,3)";
        //先将教师信息插入用户表
        getSession().createSQLQuery(sqlUser).executeUpdate();
        //插入成功后再取出用户的user_id
        Criteria criteria = getSession().createCriteria(SysUserEntity.class);
        criteria.add(Restrictions.eq("userName",sysStudentEntity.getStudentTel()));
        List<SysUserEntity> list = criteria.list();
        System.out.println("是否取出数据   "+list);
        //再插入教师详细信息表
        String sqlTeacher = "insert into sys_student(student_name,student_tel,student_sex,user_id,class_id) value('"+sysStudentEntity.getStudentName()+"','"+sysStudentEntity.getStudentTel()+"','"+sysStudentEntity.getStudentSex()+"','"+list.get(0).getUserId()+"','"+sysStudentEntity.getClassId()+"') ";
        getSession().createSQLQuery(sqlTeacher).executeUpdate();
        SessionClose();
    }

}
